import { Router } from "https://deno.land/x/oak@v12.6.0/mod.ts";
import { client, closeDB } from "../db.ts";

const ratingRouter = new Router();

// 校验函数
function validateRequestBody(body: Record<string, unknown>, requiredFields: string[]): string | null {
  for (const field of requiredFields) {
    if (!body[field]) {
      return `${field} is required`;
    }
  }
  return null;
}

// 点赞或点踩处理通用函数
// 点赞或点踩处理通用函数
async function updateRating(ctx: any, ratingType: "like" | "dislike") {
    // 从请求体获取数据
    const body = await ctx.request.body().value;
    const error = validateRequestBody(body, ["link_id", "user_id"]);
    if (error) {
      ctx.response.status = 400;
      ctx.response.body = { message: error };
      return;
    }

    // 解构请求体参数
    const { link_id, user_id } = body;

    if (!link_id || !user_id) {
      ctx.response.status = 400;
      ctx.response.body = { message: "Invalid link_id or user_id" };
      return;
    }
    const db = await client();
    try {
    // 插入或更新评分
    const ratingQuery = `
      INSERT INTO user_ratings (user_id, link_id, rating_type)
      VALUES ($1, $2, $3)
      ON CONFLICT (user_id, link_id)
      DO UPDATE SET rating_type = $3`;

    // 确保参数传递正确
    await db.queryObject(ratingQuery, user_id, link_id, ratingType);

    // 更新 raccoon_link 的评分
    const pointsField = ratingType === "like" ? "positive_points" : "negative_points";
    const decrementField = ratingType === "like" ? "negative_points" : "positive_points";

    const updateQuery = `
      UPDATE raccoon_link
      SET ${pointsField} = ${pointsField} + 1,
          ${decrementField} = GREATEST(${decrementField} - 1, 0)
      WHERE id = $1 AND status = true`;

    // 更新链接评分
    await db.queryObject(updateQuery, link_id);

    ctx.response.body = { message: `${ratingType.charAt(0).toUpperCase() + ratingType.slice(1)} added successfully` };
  } catch (error) {
    console.error(`Error in updateRating (${ratingType}): ${error.message}`);
    ctx.response.status = 500;
    ctx.response.body = { message: "Internal Server Error", error: error.message };
  }finally{
    closeDB(db)
  }
}




// 点赞
ratingRouter.post("/addPositiveRating", (ctx) => updateRating(ctx, "like"));

// 点踩
ratingRouter.post("/addNegativeRating", (ctx) => updateRating(ctx, "dislike"));

export default ratingRouter;
